/**
 *
 */
package com.honeybees.framework.common.util;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.SystemPropertyUtils;

/**
 * <dl>
 * <dt><b> 类加载器 </b></dt>
 * <p>
 * <dd></dd>
 * </dl>
 * <p>
 * Copyright (C) All rights reserved.
 * </p>
 *
 * @author 李远明
 * @since 2016-01-19 16:59:21
 */
public class ClassLoader implements ResourceLoaderAware {

    private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

    private MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(
            this.resourcePatternResolver);

    private final List<TypeFilter> includeFilters = new LinkedList<TypeFilter>();
    private final List<TypeFilter> excludeFilters = new LinkedList<TypeFilter>();

    private ClassLoader() {
    }

    /**
     * {@inheritDoc}
     *
     * @version 2016-01-21 21:45:04
     */
    // @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
        this.metadataReaderFactory = new CachingMetadataReaderFactory(resourceLoader);
    }

    public final ResourceLoader getResourceLoader() {
        return this.resourcePatternResolver;
    }

    public void addIncludeFilter(TypeFilter includeFilter) {
        this.includeFilters.add(includeFilter);
    }

    public void addExcludeFilter(TypeFilter excludeFilter) {
        this.excludeFilters.add(0, excludeFilter);
    }

    public void resetFilters(boolean useDefaultFilters) {
        this.includeFilters.clear();
        this.excludeFilters.clear();
    }

    /**
     * <dl>
     * <dt><b> 根据包名扫描指定路径下的类，可以根据注解过滤。 </b></dt>
     * <p>
     * <dd>功能描述</dd>
     * </dl>
     *
     * @param pkgPattern
     *            包名，格式：com.honeybees、com.honeybees.web.system.**.model等
     * @param annotations
     *            注解
     * @return
     * @author 李远明
     * @version 2016年1月21日 上午10:07:00
     */
    @SafeVarargs
    public static Set<Class<?>> load(String pkgPattern, Class<? extends Annotation>... annotations) {
        ClassLoader cs = new ClassLoader();
        for (Class<? extends Annotation> annotation : annotations) {
            cs.addIncludeFilter(new AnnotationTypeFilter(annotation));
        }

        Set<Class<?>> classes = cs.doScan(pkgPattern);
        return classes;
    }

    /**
     * <dl>
     * <dt><b> 根据包名扫描指定路径下的类，可以根据注解过滤。 </b></dt>
     * <p>
     * <dd>功能描述</dd>
     * </dl>
     *
     * @param pkgPatterns
     *            包名，格式：com.honeybees、com.honeybees.web.system.**.model等
     * @param annotations
     *            注解类型，比如Alias.class。
     * @return
     * @author 李远明
     * @version 2016年1月21日 上午10:07:00
     */
    /*
     * 当使用一个不可具体化的参数（Non-Reifiable Formal Parameters）调用一个可变参数方法（Varargs Methods ）
     * 编辑器会生成一个“非安全操作”的警告。
     */
    @SafeVarargs
    public static Set<Class<?>> load(String[] pkgPatterns, Class<? extends Annotation>... annotations) {
        ClassLoader cs = new ClassLoader();
        for (Class<? extends Annotation> annotation : annotations) {
            cs.addIncludeFilter(new AnnotationTypeFilter(annotation));
        }

        Set<Class<?>> classes = new HashSet<Class<?>>();
        for (String pkgPattern : pkgPatterns) {
            Set<Class<?>> classSet = cs.doScan(pkgPattern);
            classes.addAll(classSet);
        }
        return classes;
    }

    private Set<Class<?>> doScan(String pkgPattern) {
        Set<Class<?>> classes = new HashSet<Class<?>>();
        try {
            String searchLocation = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                    + org.springframework.util.ClassUtils.convertClassNameToResourcePath(
                            SystemPropertyUtils.resolvePlaceholders(pkgPattern))
                    + "/**/*.class";

            Resource[] resources = this.resourcePatternResolver.getResources(searchLocation);

            for (Resource resource : resources) {
                if (resource.isReadable()) {
                    MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);
                    if ((includeFilters.size() == 0 && excludeFilters.size() == 0) || matches(metadataReader)) {
                        try {
                            classes.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
                        } catch (ClassNotFoundException e) {
                        }
                    }
                }
            }
        } catch (IOException ex) {
            throw new BeanDefinitionStoreException("doScan I/O Exception", ex);
        }
        return classes;
    }

    protected boolean matches(MetadataReader metadataReader) throws IOException {
        for (TypeFilter tf : this.excludeFilters) {
            if (tf.match(metadataReader, this.metadataReaderFactory)) {
                return false;
            }
        }
        for (TypeFilter tf : this.includeFilters) {
            if (tf.match(metadataReader, this.metadataReaderFactory)) {
                return true;
            }
        }
        return false;
    }

    /**
     * <dl>
     * <dt><b> 标题 </b></dt>
     * <p>
     * <dd>功能描述</dd>
     * </dl>
     *
     * @param args
     * @author 李远明
     * @version 2016年1月19日 下午4:59:21
     */
    public static void main(String[] args) {
        String pkg = "com.honeybees.web.system.**.model";
        Set<Class<?>> classes = load(pkg); // , Alias.class
        for (Class<?> clazz : classes) {
            System.out.println(clazz.getName());
        }
    }

}
